package com.theme.passport.controller.app;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.theme.common.base.DateHandler;
import com.theme.common.mvc.utils.PageUtils;
import com.theme.common.mvc.view.R;
import com.theme.passport.controller.sys.AbstractController;
import com.theme.passport.entity.constant.*;
import com.theme.passport.entity.params.WidgePreviews;
import com.theme.passport.entity.theme.AlbumProductEntity;
import com.theme.passport.entity.theme.RecommendProductEntity;
import com.theme.passport.entity.theme.WidgeEntity;
import com.theme.passport.service.theme.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @name:OtherThemeController<tb>
 * @title:组件其他接口<tb>
 * @author:cuixinfu@51play.com<tb>
 * @date:2021/10/22 8:59:41<tb>
 */
@RestController
@RequestMapping("app/other-widge")
@Api("其他组件相关接口[精品组件(Banner),最新组件,今日推荐组件,热门组件]")
public class OtherWidgeController extends AbstractController {
    @Autowired
    private WidgeService widgeService;

    @Autowired
    private CarouselService carouselService;
    @Autowired
    private DownloadHistoryService downloadHistoryService;
    @Autowired
    private AlbumProductService albumProductService;
    @Autowired
    private RecommendProductService recommendProductService;

    @GetMapping("banner")
    @ApiOperation("获取轮播图组件(Banner)")
    public R banner(@RequestParam(value = "page", defaultValue = "1") String page,
                    @RequestParam(value = "limit", defaultValue = "10") String limit) {
        Map<String, Object> params = new HashMap<>();
        params.put("page", page);
        params.put("limit", limit);
        params.put("type", String.valueOf(CarouselTypeEnum.WIDGE.getValue()));
        PageUtils pages = carouselService.queryPage(params);
        return R.ok().put("page", pages);
    }


    @GetMapping("newest")
    @ApiOperation("获取最新组件[时间排序]")
    public R newest(@RequestParam(value = "page", defaultValue = "1") String page,
                    @RequestParam(value = "limit", defaultValue = "10") String limit) {
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        Map<String, Object> params = new HashMap<>();
        params.put("status", String.valueOf(status));
        params.put("themeShow", false);
        params.put("page", page);
        params.put("showStatus", 1);
        params.put("limit", limit);
        PageUtils pages = widgeService.queryPageByCreateAesc(params);
        List<WidgeEntity> listTemp = (List<WidgeEntity>) pages.getList();
        if (listTemp == null || listTemp.size() <= 0) {
            return R.ok().put("page", pages);
        }
        List<Long> widgeIds = new ArrayList<>(16);
        listTemp.forEach(widgeEntity -> {
            widgeIds.add(widgeEntity.getId());
        });
        params.put("ids", widgeIds);
        params.put("page", page);
        PageUtils pages2 = getWidgesList(params);
        return R.ok().put("page", pages2);
    }


    @GetMapping("newest/v2")
    @ApiOperation("获取最新组件[时间排序]V2")
    public R newestV2(@RequestParam(value = "page", defaultValue = "1") String page,
                    @RequestParam(value = "limit", defaultValue = "10") String limit) {
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        Map<String, Object> params = new HashMap<>();
        params.put("status", String.valueOf(status));
        params.put("themeShow", false);
        params.put("page", page);
        params.put("limit", limit);
        params.put("showStatus", 1);
        PageUtils pages = widgeService.queryPageByCreateAesc(params);
        List<WidgeEntity> listTemp = (List<WidgeEntity>) pages.getList();
        if (listTemp == null || listTemp.size() <= 0) {
            return R.ok().put("page", pages);
        }
        List<Long> widgeIds = new ArrayList<>(16);
        listTemp.forEach(widgeEntity -> {
            widgeIds.add(widgeEntity.getId());
        });
        params.put("ids", widgeIds);
        params.put("page", page);
        PageUtils pages2 = getWidgesListV2(params);
        return R.ok().put("page", pages2);
    }

    @GetMapping("newProduct")
    @ApiOperation("获取最新品组件[时间排序]")
    public R newProduct(@RequestParam(value = "page", defaultValue = "1") String page,
                        @RequestParam(value = "limit", defaultValue = "10") String limit) {
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        Map<String, Object> params = new HashMap<>();
        params.put("status", String.valueOf(status));
        params.put("showStatus", 1);
        params.put("themeShow", false);
        params.put("nts", String.valueOf(ThemeNtsEnum.YES.getValue()));
        params.put("page", page);
        params.put("limit", limit);
        PageUtils pages = widgeService.queryPageByCreateAesc(params);
        List<WidgeEntity> listTemp = (List<WidgeEntity>) pages.getList();
        if (listTemp == null || listTemp.size() <= 0) {
            return R.ok().put("page", pages);
        }
        List<Long> widgeIds = new ArrayList<>(16);
        listTemp.forEach(widgeEntity -> {
            widgeIds.add(widgeEntity.getId());
        });
        params.put("ids", widgeIds);
        params.put("page", page);
        PageUtils pages2 = getWidgesList(params);
        return R.ok().put("page", pages2);
    }


    @GetMapping("newProduct/v2")
    @ApiOperation("获取最新品组件[时间排序]V2")
    public R newProductV2(@RequestParam(value = "page", defaultValue = "1") String page,
                        @RequestParam(value = "limit", defaultValue = "10") String limit) {
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        Map<String, Object> params = new HashMap<>();
        params.put("status", String.valueOf(status));
        params.put("themeShow", false);
        params.put("nts", String.valueOf(ThemeNtsEnum.YES.getValue()));
        params.put("showStatus", 1);
        params.put("page", page);
        params.put("limit", limit);
        PageUtils pages = widgeService.queryPageByCreateAesc(params);
        List<WidgeEntity> listTemp = (List<WidgeEntity>) pages.getList();
        if (listTemp == null || listTemp.size() <= 0) {
            return R.ok().put("page", pages);
        }
        List<Long> widgeIds = new ArrayList<>(16);
        listTemp.forEach(widgeEntity -> {
            widgeIds.add(widgeEntity.getId());
        });
        params.put("ids", widgeIds);
        params.put("page", page);
        PageUtils pages2 = getWidgesListV2(params);
        return R.ok().put("page", pages2);
    }

    @GetMapping("todayRecommend")
    @ApiOperation("获取今日推荐组件")
    public R todayRecommend(@RequestParam(value = "page", defaultValue = "1") String page,
                            @RequestParam(value = "limit", defaultValue = "10") String limit) {
        List<RecommendProductEntity> recommendList = null;
        Wrapper<RecommendProductEntity> queryWrapper = new QueryWrapper<RecommendProductEntity>()
                .eq("type", AubumTypeEnum.WIDGE.getValue())
                .eq("recommend_id", 2);
        recommendList = recommendProductService.list(queryWrapper);
        if (recommendList == null) {
            queryWrapper = new QueryWrapper<RecommendProductEntity>()
                    .eq("type", AubumTypeEnum.WIDGE.getValue());
            recommendList = recommendProductService.list(queryWrapper);
        }

        List<Long> widgeIds = new ArrayList<>(16);
        recommendList.forEach(themeRecommend -> {
            widgeIds.add(themeRecommend.getObjectId());
        });
        Map<String, Object> params = new HashMap<>(6);
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        params.put("page", page);
        params.put("limit", limit);
        params.put("ids", widgeIds);
        params.put("status", String.valueOf(status));
        params.put("themeShow", false);
        PageUtils pages2 = getWidgesList(params);
        return R.ok().put("page", pages2);
    }
    @GetMapping("todayRecommend/v2")
    @ApiOperation("获取今日推荐组件v2")
    public R todayRecommendV2(@RequestParam(value = "page", defaultValue = "1") String page,
                            @RequestParam(value = "limit", defaultValue = "10") String limit) {
        List<RecommendProductEntity> recommendList = null;
        Wrapper<RecommendProductEntity> queryWrapper = new QueryWrapper<RecommendProductEntity>()
                .eq("type", AubumTypeEnum.WIDGE.getValue())
                .eq("recommend_id", 2);
        recommendList = recommendProductService.list(queryWrapper);
        if (recommendList == null) {
            queryWrapper = new QueryWrapper<RecommendProductEntity>()
                    .eq("type", AubumTypeEnum.WIDGE.getValue());
            recommendList = recommendProductService.list(queryWrapper);
        }

        List<Long> widgeIds = new ArrayList<>(16);
        recommendList.forEach(themeRecommend -> {
            widgeIds.add(themeRecommend.getObjectId());
        });
        Map<String, Object> params = new HashMap<>(6);
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        params.put("page", page);
        params.put("limit", limit);
        params.put("ids", widgeIds);
        params.put("status", String.valueOf(status));
        params.put("themeShow", false);
        PageUtils pages2 = getWidgesListV2(params);
        return R.ok().put("page", pages2);
    }
    @GetMapping("recommend")
    @ApiOperation("获取推荐组件")
    public R recommend(@RequestParam(value = "recommendId") Long recommendId,
                       @RequestParam(value = "page", defaultValue = "1") String page,
                       @RequestParam(value = "limit", defaultValue = "10") String limit) {
        List<RecommendProductEntity> recommendList = null;
        Wrapper<RecommendProductEntity> queryWrapper = new QueryWrapper<RecommendProductEntity>()
                .eq("recommend_id", recommendId);
        recommendList = recommendProductService.list(queryWrapper);
        if (recommendList == null) {
            queryWrapper = new QueryWrapper<RecommendProductEntity>()
                    .eq("type", AubumTypeEnum.WIDGE.getValue());
            recommendList = recommendProductService.list(queryWrapper);
        }

        List<Long> widgeIds = new ArrayList<>(16);
        recommendList.forEach(themeRecommend -> {
            widgeIds.add(themeRecommend.getObjectId());
        });
        Map<String, Object> params = new HashMap<>(6);
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        params.put("page", page);
        params.put("limit", limit);
        params.put("ids", widgeIds);
        params.put("status", String.valueOf(status));
        params.put("themeShow", false);
        PageUtils pages2 = getWidgesList(params);
        return R.ok().put("page", pages2);
    }
    @GetMapping("recommend/v2")
    @ApiOperation("获取推荐组件V2")
    public R recommendV2(@RequestParam(value = "recommendId") Long recommendId,
                       @RequestParam(value = "page", defaultValue = "1") String page,
                       @RequestParam(value = "limit", defaultValue = "10") String limit) {
        List<RecommendProductEntity> recommendList = null;
        Wrapper<RecommendProductEntity> queryWrapper = new QueryWrapper<RecommendProductEntity>()
                .eq("recommend_id", recommendId);
        recommendList = recommendProductService.list(queryWrapper);
        if (recommendList == null) {
            queryWrapper = new QueryWrapper<RecommendProductEntity>()
                    .eq("type", AubumTypeEnum.WIDGE.getValue());
            recommendList = recommendProductService.list(queryWrapper);
        }

        List<Long> widgeIds = new ArrayList<>(16);
        recommendList.forEach(themeRecommend -> {
            widgeIds.add(themeRecommend.getObjectId());
        });
        Map<String, Object> params = new HashMap<>(6);
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        params.put("page", page);
        params.put("limit", limit);
        params.put("ids", widgeIds);
        params.put("status", String.valueOf(status));
        params.put("themeShow", false);
        PageUtils pages2 = getWidgesListV2(params);
        return R.ok().put("page", pages2);
    }

    @GetMapping("album")
    @ApiOperation("获取组件专题列表")
    public R albumList(@RequestParam(value = "albumId") Long albumId,
                       @RequestParam(value = "page", defaultValue = "1") String page,
                       @RequestParam(value = "limit", defaultValue = "10") String limit) {
        Wrapper<AlbumProductEntity> queryWrapper = new QueryWrapper<AlbumProductEntity>()
                .eq("album_id", albumId);
        List<AlbumProductEntity> albumProductList = albumProductService.list(queryWrapper);
        List<Long> widgeIds = new ArrayList<>(16);
        albumProductList.forEach(themeRecommend -> {
            widgeIds.add(themeRecommend.getObjectId());
        });
        Map<String, Object> params = new HashMap<>(6);
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        params.put("page", page);
        params.put("limit", limit);
        params.put("ids", widgeIds);
        params.put("status", String.valueOf(status));
        params.put("themeShow", false);
        PageUtils pages2 = getWidgesList(params);
        return R.ok().put("page", pages2);
    }
    @GetMapping("album/v2")
    @ApiOperation("获取组件专题列表v2")
    public R albumListv2(@RequestParam(value = "albumId") Long albumId,
                       @RequestParam(value = "page", defaultValue = "1") String page,
                       @RequestParam(value = "limit", defaultValue = "10") String limit) {
        Wrapper<AlbumProductEntity> queryWrapper = new QueryWrapper<AlbumProductEntity>()
                .eq("album_id", albumId);
        List<AlbumProductEntity> albumProductList = albumProductService.list(queryWrapper);
        List<Long> widgeIds = new ArrayList<>(16);
        albumProductList.forEach(themeRecommend -> {
            widgeIds.add(themeRecommend.getObjectId());
        });
        Map<String, Object> params = new HashMap<>(6);
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        params.put("page", page);
        params.put("limit", limit);
        params.put("ids", widgeIds);
        params.put("status", String.valueOf(status));
        params.put("themeShow", false);
        PageUtils pages2 = getWidgesListV2(params);
        return R.ok().put("page", pages2);
    }
    @GetMapping("hot")
    @ApiOperation("获取热门组件[前七天下载量最高的]")
    public R hot(@RequestParam(value = "page", defaultValue = "1") String page,
                 @RequestParam(value = "limit", defaultValue = "10") String limit) {
        //1、根据时间查询昨天24小时（一天）
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = DateHandler.addDateDays(new Date(),-7);
        Date endDate = DateHandler.addDateDays(new Date(),-1);
        Date startTime = DateHandler.getStartTime(startDate);
        Date endTime = DateHandler.getEndTime(endDate);
        Map<String, Object> hotParams = new HashMap<>();
        hotParams.put("type", String.valueOf(DownloadTypeEnum.WIDGE.getValue()));
        hotParams.put("startTime", formatter.format(startTime));
        hotParams.put("endTime", formatter.format(endTime));
        //2、得的组件id
        List<Long> widgeIds = downloadHistoryService.queryHotDownloadIds(hotParams);
        //3、根据组件id查询
        Map<String, Object> params = new HashMap<>(6);
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        params.put("page", page);
        params.put("limit", limit);
        params.put("ids", widgeIds);
        params.put("themeShow", false);
        params.put("status", String.valueOf(status));

        params.put("showStatus", 1);
        //没有最新下的话数据正常显示几个
        if (widgeIds == null || widgeIds.size()<10){
            PageUtils pages = widgeService.queryPageBydistinctName(params);
            List<WidgeEntity> list = (List<WidgeEntity>) pages.getList();
            list.forEach(theme ->{
                //同名组件列表
                List<WidgeEntity> widgeSizeList = widgeService.queryWidgeListByName(theme.getName());
                WidgeEntity widge = widgeSizeList.get(0);
                //SysUserEntity byId = sysUserService.getById(widge.getUserId());
                //widge.setUseNickname(byId.getNickname());
                BeanUtils.copyProperties(widge,theme);
                // 同名组件大小
                WidgePreviews widgePreviews = new WidgePreviews();
                widgeSizeList.forEach(item ->{
                    String widgetSize = item.getWidgetSize();
                    if (widgetSize.equals(WidgeSizeEnum.SMALL.getValue())){
                        widgePreviews.setSmall(item.getPreview());
                    }
                    if (widgetSize.equals(WidgeSizeEnum.MEDIUM.getValue())){
                        widgePreviews.setMidium(item.getPreview());
                    }
                    if (widgetSize.equals(WidgeSizeEnum.LAREGE.getValue())){
                        widgePreviews.setLarge(item.getPreview());
                    }
                });
                theme.setWidgePreviews(widgePreviews);
                theme.setWidgeSizeList(widgeSizeList);
            });
            pages.setList(list);
            return R.ok().put("page", pages);
        }
        PageUtils pages = getWidgesList(params);
        return R.ok().put("page", pages);
    }

    @GetMapping("hot/v2")
    @ApiOperation("获取热门组件[前七天下载量最高的]V2")
    public R hotV2(@RequestParam(value = "page", defaultValue = "1") String page,
                 @RequestParam(value = "limit", defaultValue = "10") String limit) {
        //1、根据时间查询昨天24小时（一天）
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = DateHandler.addDateDays(new Date(), -7);
        Date endDate = DateHandler.addDateDays(new Date(), -1);
        Date startTime = DateHandler.getStartTime(startDate);
        Date endTime = DateHandler.getEndTime(endDate);
        Map<String, Object> hotParams = new HashMap<>();
        hotParams.put("type", String.valueOf(DownloadTypeEnum.WIDGE.getValue()));
        hotParams.put("startTime", formatter.format(startTime));
        hotParams.put("endTime", formatter.format(endTime));
        //2、得的组件id
        List<Long> widgeIds = downloadHistoryService.queryHotDownloadIds(hotParams);
        //3、根据组件id查询
        Map<String, Object> params = new HashMap<>(6);
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        params.put("page", page);
        params.put("limit", limit);
        params.put("ids", widgeIds);
        params.put("themeShow", false);
        params.put("showStatus", 1);
        params.put("status", String.valueOf(status));
        //没有最新下的话数据正常显示几个
        if (widgeIds == null || widgeIds.size() < 10) {
            PageUtils pages = widgeService.queryPageBydistinctName(params);
            List<WidgeEntity> list = (List<WidgeEntity>) pages.getList();
            List<WidgeEntity> chilendList = new ArrayList<>();
            for (WidgeEntity theme : list) {
                List<WidgeEntity> widgeSizeList = widgeService.queryWidgeListByNameV2(theme.getName());
                chilendList.addAll(widgeSizeList);
            }
            chilendList =  chilendList.stream().distinct().collect(Collectors.toList());
            for (WidgeEntity theme : list) {
                // 同名组件大小
                WidgePreviews widgePreviews = new WidgePreviews();
                for (WidgeEntity citem : chilendList) {
                    if (theme.getName().equals(citem.getName())) {
                        String widgetSize = citem.getWidgetSize();
                        if (widgetSize.equals(WidgeSizeEnum.SMALL.getValue())) {
                            widgePreviews.setSmall(citem.getPreview());
                        }
                        if (widgetSize.equals(WidgeSizeEnum.MEDIUM.getValue())) {
                            widgePreviews.setMidium(citem.getPreview());
                        }
                        if (widgetSize.equals(WidgeSizeEnum.LAREGE.getValue())) {
                            widgePreviews.setLarge(citem.getPreview());
                        }
                        BeanUtils.copyProperties(citem, theme);
                    }
                }
                theme.setWidgePreviews(widgePreviews);
            }
            List<WidgeEntity> returnList = new ArrayList<>();
            for (WidgeEntity item : list) {
                for (WidgeEntity citem : chilendList) {
                    if (item.getName().equals(citem.getName())) {
                        WidgeEntity entity = new WidgeEntity();
                        BeanUtils.copyProperties(item, entity);
                        List<WidgeEntity> tempList = new ArrayList<>();
                        tempList.add(citem);
                        entity.setWidgeSizeList(tempList);
                        entity.setWidgetSize(tempList.get(0).getWidgetSize());
                        returnList.add(entity);
                    }
                }
            }

            pages.setList(returnList);
            return R.ok().put("page", pages);
        }
        PageUtils pages = getWidgesListV2(params);
        return R.ok().put("page", pages);
    }


    private PageUtils getWidgesList(Map<String, Object> params) {
        PageUtils pages = widgeService.queryPageBydistinctNameByIds(params);
        List<WidgeEntity> list = (List<WidgeEntity>) pages.getList();
        list.forEach(theme ->{
            //同名组件列表
            List<WidgeEntity> widgeSizeList = widgeService.queryWidgeListByName(theme.getName());
            WidgeEntity widge = widgeSizeList.get(0);
            BeanUtils.copyProperties(widge,theme);
            // 同名组件大小
            WidgePreviews widgePreviews = new WidgePreviews();
            widgeSizeList.forEach(item ->{
                String widgetSize = item.getWidgetSize();
                if (widgetSize.equals(WidgeSizeEnum.SMALL.getValue())){
                    widgePreviews.setSmall(item.getPreview());
                }
                if (widgetSize.equals(WidgeSizeEnum.MEDIUM.getValue())){
                    widgePreviews.setMidium(item.getPreview());
                }
                if (widgetSize.equals(WidgeSizeEnum.LAREGE.getValue())){
                    widgePreviews.setLarge(item.getPreview());
                }
            });
            theme.setWidgePreviews(widgePreviews);
            theme.setWidgeSizeList(widgeSizeList);
        });



        list = list.stream().sorted(Comparator.comparing(WidgeEntity::getUpdated).reversed()).collect(Collectors.toList());

        pages.setList(list);

        return pages;
    }


    private PageUtils getWidgesListV2(Map<String, Object> params) {
        PageUtils pages = widgeService.queryPageBydistinctNameByIdsV2(params);
        List<WidgeEntity> list = (List<WidgeEntity>) pages.getList();
        List<WidgeEntity> chilendList = new ArrayList<>();
        for (WidgeEntity theme : list) {
            List<WidgeEntity> widgeSizeList = widgeService.queryWidgeListByNameV2(theme.getName());
            chilendList.addAll(widgeSizeList);
        }
        for (WidgeEntity theme : list) {
            // 同名组件大小
            WidgePreviews widgePreviews = new WidgePreviews();
            for (WidgeEntity citem : chilendList) {
                if (theme.getName().equals(citem.getName())) {
                    String widgetSize = citem.getWidgetSize();
                    if (widgetSize.equals(WidgeSizeEnum.SMALL.getValue())) {
                        widgePreviews.setSmall(citem.getPreview());
                    }
                    if (widgetSize.equals(WidgeSizeEnum.MEDIUM.getValue())) {
                        widgePreviews.setMidium(citem.getPreview());
                    }
                    if (widgetSize.equals(WidgeSizeEnum.LAREGE.getValue())) {
                        widgePreviews.setLarge(citem.getPreview());
                    }
                    BeanUtils.copyProperties(citem, theme);
                }
            }
            theme.setWidgePreviews(widgePreviews);
        }
        List<WidgeEntity> returnList = new ArrayList<>();
        for (WidgeEntity item : list) {
            for (WidgeEntity citem : chilendList) {
                if (item.getName().equals(citem.getName())) {
                    WidgeEntity entity = new WidgeEntity();
                    BeanUtils.copyProperties(item, entity);
                    List<WidgeEntity> tempList = new ArrayList<>();
                    tempList.add(citem);
                    entity.setWidgeSizeList(tempList);
                    entity.setWidgetSize(tempList.get(0).getWidgetSize());
                    returnList.add(entity);
                }
            }
        }

        pages.setList(returnList);

        return pages;
    }



}
